package com.mgy.mock;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;


import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.util.Set;
import java.util.Stack;
import java.util.UUID;

/**
 * xxx
 *
 * @author maguoyong
 * @date 2021/6/3
 */
public class SvgToPng {

    public static final Stack<ChromeDriver> STACK = new Stack<>();

    public static final String DIR = "/Users/admin/Downloads/";

    static {
        //此处填写驱动程序，前面是驱动名随浏览器改变，后面是你对应驱动程序的文件位置
//        System.setProperty(
//                "webdriver.chrome.driver",
//                "/workspace/learning/software/chromedriver");
//
//        ChromeOptions chromeOptions = new ChromeOptions();
////        chromeOptions.addArguments("--headless"); // 隐藏窗口
//        chromeOptions.addArguments("--window-size=4000,1600");
//        ChromeDriver driver = new ChromeDriver(chromeOptions);
//        STACK.push(driver);

    }


    public static byte[] toPngByte(ChromeDriver driver, String svgContent, String uuid) {
        String path = DIR + uuid;
        try {
            String svg1 = "<svg id=\" " + uuid + " \"  " + svgContent.substring(4);
            String html = "<html><head>" + uuid + "</head><body> " + svg1 + "</body></html>";
            try (FileWriter writer = new FileWriter(path)) {
                writer.write(html);
            }
            driver.executeScript("window.open('" + path + "')");
            synchronized (driver) {
                WebDriver webDriver = null;
                Set<String> sets = driver.getWindowHandles();
                for (String handle : sets) {
                    webDriver = driver.switchTo().window(handle);
                    if (StringUtils.equals(webDriver.getTitle(), uuid)) {
                        break;
                    }
                }
                WebElement webElement = driver.findElementById(uuid);

                byte[] bytes = webElement.getScreenshotAs(OutputType.BYTES);
                driver.close();
                return bytes;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtils.deleteQuietly(new File(path));
        }
        return null;
    }

    public static void toPng(byte[] bytes, String path) {
        try (FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path))) {
            imageOutput.write(bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
